<template>
  <el-form :model="form" ref="form" :label-position="labelPosition" :hide-required-asterisk="true" :size="'mini'" style="margin:0 20px;">
    <el-row>
      <el-col :span="24" v-if="type_info === '编辑'">
        <el-form-item :label="$t('接口名称')" :label-width="formLabelWidthHalf" prop="strBridgeName" @input="updateView($event)">
          <span>{{form.strSubinterfaceName}}</span>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('接口别名')" prop="cDevOtherName" :label-width="formLabelWidthHalf" @input="updateView($event)">
          <el-input id="subInterface-cDevOtherName" v-model="form.cDevOtherName" style="width:250px;"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :rules="$rules.iMtuSubInterface" label="MTU" prop="iMtu" :label-width="formLabelWidthHalf" @input="updateView($event)">
          <el-input id="subInterface-iMtu" v-emoji v-model="form.iMtu" style="width:250px;"></el-input>
          <el-tooltip class="item" effect="light" :content="$t('最小值为68，最大值根据父接口的MTU值决定。')" placement="top">
            <i class="el-icon-warning-outline" style="color:#E6A23C;font-size:16px;"></i>
          </el-tooltip>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :rules="$rules.isRequired" :label="$t('主接口名称')" prop="strPhysicsName" :label-width="formLabelWidthHalf" @input="updateView($event)">
          <el-select :disabled="type_info === '编辑'" v-model="form.strPhysicsName" filterable size='small' style="width:250px;">
            <el-option :id="`subInterface-strPhysicsName-${item}`" v-for="item in strPhysicsList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('状态')" :label-width="formLabelWidth" prop="bPortStatus" :rules="$rules.isRequired">
          <el-radio-group v-model="form.bPortStatus">
            <el-radio id="subInterface-bPortStatus-up" label="up" class="up">{{$t('开启')}}</el-radio>
            <el-radio id="subInterface-bPortStatus-down" label="down" class="down">{{$t('关闭')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('模式')" :label-width="formLabelWidth">
          <el-radio-group v-model="form.enPortMode">
            <el-radio id="subInterface-enPortMode0" :label="0" class="routerMode">{{$t('路由模式')}}</el-radio>
            <el-radio id="subInterface-enPortMode1" :label="1" class="transparent">{{$t('透明模式')}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :rules="$rules.vlanTag" :label="$t('VLAN Tag')" prop="vlanTag" :label-width="formLabelWidthHalf" @input="updateView($event)">
          <el-input id="subInterface-vlanTag" v-emoji :disabled="type_info === '编辑'" v-model="form.vlanTag" ref="name" style="width:250px;" autocomplete="off"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="form.enPortMode===1">
        <el-form-item :rules="$rules.iVlanId" :label="$t('Access VLAN ID')" prop="iVlanId" :label-width="formLabelWidth" @input="updateView($event)">
          <el-input id="subInterface-iVlanId" v-emoji v-model="form.iVlanId" ref="iVlanId" style="width:250px;"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-tabs v-model="activeName" type="card" @tab-click="handleClick" v-if="form.enPortMode===0">
      <el-tab-pane label="IPv4" name="ipv4">
        <!--    添加对象页面-->
        <div>
          <el-button type="success" :size="'small'" @click="add_addr">{{$t('添加')}}</el-button>
          <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" v-if="dialogAddrFormVisible" :visible.sync="dialogAddrFormVisible" width="550px" append-to-body>
            <el-form :model="add_ipv4_form" :rules="add_rules" :hide-required-asterisk="true" ref="add_ipv4_form" class="demo-ruleForm">
              <el-form-item :label="$t('IP地址')" :label-width="formLabelWidth" :prop="'ipv4'">
                <el-input id="subInterface-ipv4" v-emoji v-model="add_ipv4_form.ipv4" ref="ip" style="width:217px;" size='small'></el-input>
              </el-form-item>
              <el-form-item :label="$t('子网掩码')" :label-width="formLabelWidth" :prop="'mask'">
                <el-input id="subInterface-mask" v-emoji v-model="add_ipv4_form.mask" ref="mask" style="width:217px;" size='small'></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button id="subInterface-ipv4-submit" type="primary" @click="submitForm('add_ipv4_form')">{{$t('确 定')}}</el-button>
              <el-button id="subInterface-ipv4-cancel" @click="dialogAddrFormVisible = false">{{$t('取 消')}}</el-button>
            </div>
          </el-dialog>

          <el-table size='mini' :data="form.ipv4" stripe border style="width: 100%;margin-top: 5px">
            <el-table-column prop='cPortIpv4' label="IPv4" align="center">
              <template slot-scope="scope">
                <tooltip :html="scope.row.cPortIpv4" :content="scope.row.cPortIpv4" class="wid190" :refName="scope.row.cPortIpv4">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column prop='cPortNetmask' :label="$t('子网掩码')" align="center">
              <template slot-scope="scope">
                <tooltip :html="scope.row.cPortNetmask" :content="scope.row.cPortNetmask" class="wid190" :refName="scope.row.cPortNetmask">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('操作')" width="100" align="center">
              <template slot-scope="scope">
                <el-button id="subInterface-ipv4-del" @click.native.prevent="deleteRow(scope.$index, form.ipv4)" type="danger" plain size="mini">
                  {{$t('删除')}}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="IPv6" name="ipv6">
        <!--    添加对象页面-->
        <div v-if="loading === 'ipv6'">
          <el-button type="success" :size="'small'" @click="add_addr">{{$t('添加')}}</el-button>
          <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" v-if="dialogAddrFormVisible" :visible.sync="dialogAddrFormVisible" width="550px" append-to-body>
            <el-form :model="add_ipv6_form" :rules="add_rules" :hide-required-asterisk="true" ref="add_ipv6_form" class="demo-ruleForm">
              <el-form-item :label="$t('IP地址')" :label-width="formLabelWidth" :prop="'ipv6'">
                <el-input id="subInterface-ipv6" v-emoji v-model="add_ipv6_form.ipv6" ref="ip" style="width:217px;" size='small'></el-input>
              </el-form-item>
              <el-form-item :label="$t('前缀长度')" :label-width="formLabelWidth" :prop="'ex_len'">
                <el-input id="subInterface-ex_len" v-emoji v-model.number="add_ipv6_form.ex_len" ref="mask" style="width:217px;" size='small'></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button id="subInterface-ip6-submit" type="primary" @click="submitForm_ipv6('add_ipv6_form')">{{$t('确 定')}}</el-button>
              <el-button id="subInterface-ip6-cancel" @click="dialogAddrFormVisible = false">{{$t('取 消')}}</el-button>
            </div>
          </el-dialog>

          <el-table size='mini' :data="form.ipv6" stripe border style="width: 100%;margin-top: 5px">
            <el-table-column prop='cPortIpv6' label="IPv6" align="center">
              <template slot-scope="scope">
                <tooltip :html="scope.row.cPortIpv6" :content="scope.row.cPortIpv6" class="wid190" :refName="scope.row.cPortIpv6">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column prop='cDevIpv6Prefix' :label="$t('前缀长度')" align="center">
              <template slot-scope="scope">
                <tooltip :html="scope.row.cDevIpv6Prefix" :content="scope.row.cDevIpv6Prefix" class="wid190" :refName="scope.row.cDevIpv6Prefix">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('操作')" width="100" align="center">
              <template slot-scope="scope">
                <el-button id="subInterface-ip6-del" @click.native.prevent="deleteRow(scope.$index, form.ipv6)" type="danger" plain size="mini">
                  {{$t('删除')}}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

  </el-form>

</template>

<script>
import { getPhysicalApiArray  } from '@/api/network/api/physical.js'
import { getBondArray } from '@/api/network/api/bond'
export default {
  inject: ['reload'],
  props: [
    'dialogFormVisible',
    'type_info',
    'edit_form'
  ],
  name: 'VirtualEdit',
  data () {
    const add_ipv4 = (rule, value, callback) => {
      if (!String(value).trim()) {
        return callback(new Error(this.$t('IP不能为空')))
      }
      if (!this.isValidIP(value)) {
        callback(new Error(this.$t('请输入正确的ip地址')))
      } else {
        callback()
      }
    }
    const mask = (rule, value, callback) => {
      if (!String(value).trim()) {
        return callback(new Error(this.$t('子网掩码不能为空')))
      }
      if (!this.isValidMask(value)) {
        callback(new Error(this.$t('请输入正确的子网掩码')))
      } else {
        callback()
      }
    }
    const add_ipv6 = (rule, value, callback) => {
      if (!String(value).trim()) {
        return callback(new Error(this.$t('IP不能为空')))
      }
      if (!this.isValidIPv6(value)) {
        callback(new Error(this.$t('请输入正确的ip地址')))
      } else {
        callback()
      }
    }
    const add_ex_len = (rule, value, callback) => {
      if (Number(value) < 1 || Number(value) > 128) {
        callback(new Error(this.$t('前缀长度的范围是1-128')))
      } else {
        callback()
      }
    }
    return {
      transferData: [],
      old_name: {},
      old_desc: '',
      old_form: {},
      strPhysicsList:[],
      form: {
        strPhysicsName:'',
        strBridgeName: '',
        cDevOtherName: '',
        iVlanId: '',
        enPortMode: 0,
        bPortStatus: 'up',
        bLinkStatus: '',
        vlanTag:'',
        iMtu:'1500',
        ipv4: [],
        ipv6: []
      },
      formCopy: {
        strPhysicsName:'',
        strBridgeName: '',
        cDevOtherName: '',
        iVlanId: '',
        bPortStatus: 'up',
        bLinkStatus: '',
        vlanTag:'',
        iMtu:'1500',
        ipv4: [],
        ipv6: []
      },
      add_rules: {
        ipv4: [
          { validator: add_ipv4, trigger: 'blur' }
        ],
        mask: [
          { validator: mask, trigger: 'blur' }
        ],
        ipv6: [
          { validator: add_ipv6, trigger: 'blur' }
        ],
        ex_len: [
          { required: true, message: '前缀长度不能为空' },
          { type: 'number', message: '前缀长度必须为数字值' },
          { validator: add_ex_len, trigger: 'blur' }
        ]
      },
      add_ipv4_form: {},
      add_ipv6_form: {},
      formLabelWidth: '150px',
      formLabelWidthHalf: '150px',
      dialogAddrFormVisible: false,
      labelPosition: 'left',
      activeName: 'ipv4',
      loading: '',
      bLinkStatusList: { 0: 'down', 1: 'up' }
    }
  },
  watch: {
    edit_form: {
      handler (val) {
        if (this.type_info === '编辑') {
          this.form = Object.assign(this.form, val)
          this.old_name = val.name
          this.old_desc = val.desc
          this.old_form = JSON.parse(JSON.stringify(val))
        } else {
          this.form = Object.assign(this.form, val)
        }
      },
      immediate: true
    },
    'dialogAddrFormVisible': {
      handler (val) {
        if (val === false) {
          this.add_ipv4_form = {}
          this.add_ipv6_form = {}
          if (this.$refs['add_ipv4_form'] !== undefined) {
            this.$refs['add_ipv4_form'].resetFields()
          }
          if (this.$refs['add_ipv6_form'] !== undefined) {
            this.$refs['add_ipv6_form'].resetFields()
          }
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.getPhysicalApiArray();
  },
  methods: {
    // 获取物理接口
    async getPhysicalApiArray() {
     const resp = await getPhysicalApiArray();
     let bondArray = await getBondArray();
      bondArray = bondArray.info.map(item=>item.BondName);
     let strPhysicsList = resp.info.filter(item=>[0,1].includes(item.enPortMode) && item.enPortType===0)
     strPhysicsList = strPhysicsList.map(item=>item.strPhysicsName);
     this.strPhysicsList = [...strPhysicsList,...bondArray];
     console.log('this.strPhysicsList',this.strPhysicsList);
    },
    // 发送form表单数据到父组件
    send_form () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = {}
          if(this.type_info === '添加') {
            params = {
          ...this.form,
          ipv4:JSON.stringify(this.form.ipv4),
          ipv6:JSON.stringify(this.form.ipv6),
           }
        }else {
          const old_form =  {
            ...this.old_form,
          }
          const new_form =  {
            ...this.form,
          }
          params = {
            old_form:JSON.stringify(old_form),
            new_form:JSON.stringify(new_form),
          }
        }
      this.$emit('childForm', params)
        } else {
          return false
        }
      })
      
    },
    updateView (e) {
      this.$forceUpdate()
    },
    add_addr () {
      this.dialogAddrFormVisible = true
    },
    backParent () {
      this.$emit('quxiao', false)
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    handleClick (tab, event) {
      this.loading = tab.name
    },
    isValidIP (ip) {
      let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(ip)
    },
    isValidMask (mask) {
      let reg = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(255|254|252|248|240|224|192|128|0)$/
      return reg.test(mask)
    },
    isValidIPv6 (ip) {
      // let reg = /^\s*((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\d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3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
      return reg.test(ip)
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let new_ipv4 = {}
          new_ipv4.cPortIpv4 = this.add_ipv4_form.ipv4
          new_ipv4.cPortNetmask = this.add_ipv4_form.mask
          this.form.ipv4.push(new_ipv4)
          this.dialogAddrFormVisible = false
        } else {
          return false
        }
      })
    },
    submitForm_ipv6 (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let new_ipv6 = {}
          new_ipv6.cPortIpv6 = this.add_ipv6_form.ipv6
          new_ipv6.cDevIpv6Prefix = this.add_ipv6_form.ex_len
          this.form.ipv6.push(new_ipv6)
          this.dialogAddrFormVisible = false
        } else {
          return false
        }
      })
    },
    close () {
      this.form = Object.assign({}, this.formCopy)
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>

<style scoped>
.tools_box {
  text-align: left;
}
.circle {
  padding: 5px;
}
.warning_span {
  margin-left: 3%;
  color: red;
}
</style>
